package com.apes.framework.plugin.filereader.xml;

import com.apes.framework.api.ApesParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Element;

import java.util.List;


/**
 * 功能：节点解析器
 *
 * @author xul
 * @create 2018-04-16 11:54
 */
@Slf4j
public abstract class AbstractNodeParser implements ApesNodeParser<Element, ApesElement> {
    protected final Logger logger = LogManager.getLogger(this.getClass());
    /**
     * 功能：解析节点
     */
    @Override
    public ApesElement parse(Element node) {
        try {
            return parse(node, null);
        } catch (Exception e) {
            logger.error(e);
        }
        return null;
    }

    /**
     * 功能：解析节点元素
     */
    protected ApesElement parse(Element node, ApesElement parent) {
        return parse(node.getName(), node.elements(), node.attributes(), node.getTextTrim(), parent);
    }

    public ApesElement parse(String name, List<Element> elements, List<Attribute> attributes, String text, ApesElement parent) {
        /**创建节点元素**/
        ApesElement element = createElement(parent, name);
        element.setText(text);

        /**遍历节点的所有属性**/
        attributes.stream().forEach(attribute -> setAttribute(element, attribute));

        /**设置特殊节点默认属性值**/
        setDefaultValue(element);

        /**遍历节点的所有子节点**/
        elements.stream().forEach(e -> {
            ApesElement nestedElement = parse(e, element);
            setNestedElement(element, nestedElement);
        });

        return element;
    }

    /**
     * 功能：设置节点属性值
     **/
    protected void setAttribute(ApesElement element, Attribute attribute) {
        element.setAttribute(attribute.getName(), attribute.getValue());
    }

    /**
     * 功能：设置特殊节点默认属性值
     **/
    protected void setDefaultValue(ApesElement element) {
    }

    /**
     * 功能：创建节点元素
     **/
    protected ApesElement createElement(ApesElement parent, String name) {
        ApesElement element = new SimpleApesElement();
        element.setName(name);
        element.setParent(parent);
        ApesParser parser = getApesElementParser(name);
        element.setParser(parser);
        return element;
    }

    /**
     * 功能：设置子节点
     **/
    protected void setNestedElement(ApesElement element, ApesElement nestedElement) {
        element.setNestedElement(nestedElement);
    }

    protected ApesParser getApesElementParser(String elementName) {
        String key = ApesXmlParser.getKey(getDomain(), elementName);
        ApesParser parser = ApesXmlParser.getApesElementParser(key);
        if (parser == null) {
            key = ApesXmlParser.getKey(getDomain(), "default");
            parser = ApesXmlParser.getApesElementParser(key);
        }
        if (parser == null) {
            throw new RuntimeException("节点：" + elementName + "没有设置解析器！");
        }
        return parser;
    }

}
